<template>
  <div class="data-move">
    <je-panel>
      <template #tbar>
        <div class="top">
          <je-button type="text" @click="handleAdd">
            <i class="fal fa-plus-circle"></i> 添加
          </je-button>
          <je-button type="text" @click="handleUpdate"> <i class="fal fa-save"></i> 保存</je-button>
          <je-button type="text" @click="handleDelete">
            <i class="fal fa-times"></i> 删除</je-button
          >
        </div>
      </template>
      <template #default>
        <div class="table">
          <je-table
            ref="xTable"
            border
            stripe
            auto-resize
            sync-resize
            show-overflow="ellipsis"
            keep-source
            draggable
            show-header-overflow
            resizable
            header-align="center"
            height="100%"
            :scroll-y="{ mode: 'wheel' }"
            :edit-config="{
              trigger: 'click',
              mode: 'cell',
              showUpdateStatus: true,
            }"
            :row-config="{ isCurrent: true, isHover: true }"
            :loading="loading"
            :edit-rules="validRules"
            :store="tableData"
            size="mini"
            id-property="JE_CORE_DATAFLOW_ID"
            @checkbox-change="selectionChange"
            @checkbox-all="selectionChange"
            @drop="dataMoveItemDrop"
          >
            <je-table-column type="checkbox" width="40" align="center"></je-table-column>
            <je-table-column
              field="SY_ORDERINDEX"
              title="序号"
              width="80"
              align="center"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                {{ row.SY_ORDERINDEX }}
              </template>
            </je-table-column>
            <je-table-column title="启动条件" width="100" align="center" field="DATAFLOW_QYTJ">
              <template #default="{ row }">
                <je-tooltip placement="top" title="编辑">
                  <span @click="clickAction(row)"
                    ><i
                      class="fas fa-bolt"
                      :style="`color:${
                        changeJsListener(row.DATAFLOW_QYTJ) ? '#F4CE4A' : '#8d98ab'
                      } `"
                    ></i
                  ></span>
                </je-tooltip>
              </template>
            </je-table-column>
            <je-table-column
              field="DATAFLOW_DZ"
              title="动作"
              align="center"
              width="300"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.DATAFLOW_DZ"
                  mode="multiple"
                  :max-tag-count="1"
                  :show-search="false"
                  allow-clear
                  show-arrow
                >
                  <je-select-option
                    v-for="(item, index) in arrDataFlowDZ"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectMultipleLabel(row.DATAFLOW_DZ, arrDataFlowDZ, 'code', 'text')
              }}</template>
            </je-table-column>
            <je-table-column
              field="DATAFLOW_CZFS"
              title="操作方式"
              width="140"
              align="center"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select v-model:value="row.DATAFLOW_CZFS" allow-clear>
                  <je-select-option
                    v-for="(item, index) in arrDataFlowCZFS"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectLabel(row.DATAFLOW_CZFS, arrDataFlowCZFS, 'code', 'text')
              }}</template>
            </je-table-column>
            <je-table-column
              field="DATAFLOW_CZ"
              title="操作"
              width="140"
              align="center"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select v-model:value="row.DATAFLOW_CZ" allow-clear>
                  <je-select-option
                    v-for="(item, index) in arrDataFlowCZ"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </template>
              <template #default="{ row }">{{
                getSelectLabel(row.DATAFLOW_CZ, arrDataFlowCZ, 'code', 'text')
              }}</template>
            </je-table-column>
            <je-table-column
              field="DATAFLOW_SQL"
              title="SQL"
              min-width="220"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #edit="{ row }">
                <je-input v-model:value="row.DATAFLOW_SQL">
                  <template #suffix>
                    <i class="setIcon fal fa-cog" @click="showSql('DATAFLOW_SQL', row)"></i>
                  </template>
                </je-input>
              </template>
            </je-table-column>
            <je-table-column title="回调" width="100" align="center" field="DATAFLOW_HD">
              <template #default="{ row }">
                <je-tooltip placement="top" title="编辑">
                  <span @click="clickFunction(row)"
                    ><i
                      class="fas fa-bolt"
                      :style="`color:${changeJsListener(row.DATAFLOW_HD) ? '#F4CE4A' : '#8d98ab'} `"
                    ></i
                  ></span>
                </je-tooltip>
              </template>
            </je-table-column>
            <je-table-column
              field="DATAFLOW_BZ"
              title="备注"
              min-width="220"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #edit="{ row }">
                <je-input v-model:value="row.DATAFLOW_BZ" />
              </template>
            </je-table-column>
          </je-table>
        </div>
      </template>
    </je-panel>
    <div v-if="modalOption.modalFlag">
      <component
        :is="modalOption.activeModal"
        :visble="modalOption.modalFlag"
        :record-data="recordData"
        @changeModal="changeModal"
      ></component>
    </div>
  </div>
</template>

<script>
  import { ref, reactive, defineComponent, toRefs, onMounted } from 'vue';
  import { Tooltip } from 'ant-design-vue';
  import { Grid, Modal, Panel, Button, Input, Select, Data } from '@jecloud/ui';

  import { DATA_MOVE_COMPONENTS } from '@/helper/data-move-components';

  import { DATAFLOW_DZ, DATAFLOW_CZFS, DATAFLOW_CZ } from '@/helper/constant';

  import { DataMoveGet, DataMoveSave, DataMoveUpdate, DataMoveRemove } from '@/api/index';

  import { listenerEditorModal } from '@/helper/index.js';
  import { showFuncQuerys } from '@jecloud/func';
  import { useFuncStore } from '@/store/func-store';

  export default defineComponent({
    name: 'DataMove',
    components: {
      JeInput: Input,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeModal: Modal,
      JeButton: Button,
      JeTooltip: Tooltip,
      JePanel: Panel,
      ...DATA_MOVE_COMPONENTS,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    setup(props, { emit }) {
      const state = reactive({
        xTable: ref(),
        visible: false,
        title: '',
        arrDataFlowDZ: DATAFLOW_DZ,
        arrDataFlowCZFS: DATAFLOW_CZFS,
        arrDataFlowCZ: DATAFLOW_CZ,
        funcId: props.recordData.JE_CORE_FUNCINFO_ID,
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        selectTableData: [],
        loading: true,
        validRules: ref({
          DATAFLOW_DZ: [
            { required: true, message: '该输入项为必填项' },
            {
              validator({ cellValue }) {
                if (cellValue && cellValue.length <= 0) {
                  return new Error('该输入项为必填项');
                }
              },
            },
          ],
          DATAFLOW_CZFS: [{ required: true, message: '该输入项为必填项' }],
          DATAFLOW_CZ: [{ required: true, message: '该输入项为必填项' }],
          DATAFLOW_SQL: [{ required: true, message: '该输入项为必填项' }],
        }),
      });

      const modalOption = reactive({
        modalFlag: false, // 默认modal都是隐藏的false
        activeModal: '', // 默认没有激活的弹窗类型
      });

      const methods = {
        dataMoveItemDrop() {
          state.tableData.data.forEach((item, index) => {
            item.SY_ORDERINDEX = index + 1;
          });
        },
        // 点击自定义sql
        showSql(key, row) {
          showFuncQuerys({
            value: row.DATAFLOW_SQL,
            funcId: props.recordData.JE_CORE_FUNCINFO_ID,
            callback: (val) => {
              row[key] = val;
            },
          });
          // sqlEditorModal({
          //   funcId: props.recordData.JE_CORE_FUNCINFO_ID,
          //   funcCode: props.recordData.FUNCINFO_FUNCCODE,
          //   callback: (val) => {
          //     row[key] = val;
          //   },
          // });
        },
        // 点击回调
        clickFunction(row) {
          const DATAFLOW_HD = row.DATAFLOW_HD || '';
          const funcStore = useFuncStore();
          listenerEditorModal({
            funcId: funcStore.funcBean.id,
            eventType: 'default',
            title: '回调(Ctrl+S保存)',
            eventInfo: DATAFLOW_HD,
            callback: (obj) => {
              Modal.message('保存成功', 'success');
              row.DATAFLOW_HD = obj.data;
            },
          });
        },
        changeJsListener(data) {
          const parseData = data ? JSON.parse(data) : [];
          let eventType = false;
          parseData.forEach((item) => {
            if (item.fire == '1') {
              eventType = true;
            }
          });
          return eventType;
        },
        // 点击启动条件
        clickAction(row) {
          const DATAFLOW_QYTJ = row.DATAFLOW_QYTJ || '';
          const funcStore = useFuncStore();
          listenerEditorModal({
            funcId: funcStore.funcBean.id,
            eventType: 'default',
            title: '启用条件(Ctrl+S保存)',
            eventInfo: DATAFLOW_QYTJ,
            callback: (obj) => {
              Modal.message('保存成功', 'success');
              row.DATAFLOW_QYTJ = obj.data;
            },
          });
        },
        showModal(obj) {
          modalOption.modalFlag = true;
          modalOption.activeModal = obj.type;
        },

        changeModal(obj) {
          modalOption.modalFlag = obj.visible;
          obj.isRefresh && methods.getData();
        },

        selectionChange(obj) {
          state.selectTableData = obj.records;
        },

        getSelectLabel(value, list, valueProp = 'value', labelField = 'label') {
          const item = list.find((item) => item[valueProp] === value);
          return item ? item[labelField] : null;
        },

        getSelectMultipleLabel(value, list, valueProp = 'value', labelField = 'label') {
          return value
            .map((val) => {
              const item = list.find((item) => item[valueProp] === val);
              return item ? item[labelField] : null;
            })
            .join(', ');
        },

        getData() {
          const params = {
            tableCode: 'JE_CORE_DATAFLOW',
            baseSql: ` and DATAFLOW_FUNCINFO_ID = '${state.funcId}'`,
            funcId: state.funcId,
            j_query: JSON.stringify({
              custom: [
                {
                  code: 'DATAFLOW_FUNCINFO_ID',
                  value: state.funcId,
                  type: '=',
                  cn: 'and',
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
            // page: 1,
            // start: 0,
            // limit: -1,
          };
          DataMoveGet(params)
            .then((res) => {
              const data = res.data.rows || [];

              data.forEach((item) => {
                item.DATAFLOW_DZ = item.DATAFLOW_DZ ? item.DATAFLOW_DZ.split(',') : [];
              });
              state.tableData.loadData(data);

              state.loading = false;
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleAdd() {
          let index = state.tableData.data.length + 1;

          // state.tableData.data.forEach((item) => {
          //   if (item.SY_ORDERINDEX > index) {
          //     index = item.SY_ORDERINDEX;
          //   }
          // });

          const params = {
            tableCode: 'JE_CORE_DATAFLOW',
            SY_ORDERINDEX: index,
            DATAFLOW_FUNCINFO_ID: state.funcId,
          };

          DataMoveSave(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              const { data } = res;
              data.DATAFLOW_DZ = data.DATAFLOW_DZ ? data.DATAFLOW_DZ.split(',') : [];
              state.tableData.insert(data, -1);
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleUpdate() {
          const updateRecords = state.tableData.getChanges();

          state.xTable.$plugin.fullValidate(state.tableData.data, (errMap) => {
            if (errMap) {
              return false;
            }
            if (updateRecords.length === 0) {
              Modal.message('无数据操作!', 'info');
              return false;
            }

            const data = [];
            const changeData = [];
            updateRecords.forEach((item) => {
              data.push(item._record);
              const changeItem = {
                JE_CORE_DATAFLOW_ID: item._record.JE_CORE_DATAFLOW_ID,
              };
              Object.keys(item).forEach((key) => {
                if (key != '_record') {
                  changeItem[key] = item[key].newValue || '';
                }
                if (key == 'DATAFLOW_DZ') {
                  changeItem[key] = item[key].newValue.join(',');
                }
              });
              changeData.push(changeItem);
            });
            const params = {
              tableCode: 'JE_CORE_DATAFLOW',
              funcId: state.funcId,
              strData: JSON.stringify(changeData),
            };
            DataMoveUpdate(params)
              .then((res) => {
                data.forEach((item) => {
                  state.tableData.commitRecord(item);
                });
                Modal.message(res.message, 'success');
              })
              .catch((error) => {
                Modal.alert(error.message, 'error');
              });
          });
        },

        handleDelete() {
          const len = state.selectTableData.length;

          if (len === 0) {
            Modal.alert('请选择要删除的数据！', 'warning');
            return false;
          }

          Modal.confirm('确定删除选中的数据吗？', () => {
            methods.doDelete();
          });
        },

        doDelete() {
          const ids = state.selectTableData.map((item) => item.JE_CORE_DATAFLOW_ID).join(',');

          const params = {
            tableCode: 'JE_CORE_DATAFLOW',
            ids,
          };

          DataMoveRemove(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              state.selectTableData.forEach((item) => {
                state.tableData.remove(item);
              });
              state.selectTableData = [];
              // methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
      };

      onMounted(() => {
        methods.getData();
      });

      return {
        ...toRefs(state),
        ...methods,
        modalOption,
      };
    },
  });
</script>
<style lang="less" scoped>
  .data-move {
    // position: relative;
    width: 100%;
    height: 100%;
    .top {
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0 20px 0 4px;
      background: #f7f9fc;
      > .ant-btn {
        padding: 4px 12px !important;
        &:hover {
          color: #3f3f3f !important;
          background: #d9d9d9 !important;
        }
      }
    }
    .table {
      // position: absolute;
      // width: 100%;
      // top: 40px;
      // bottom: 0;
      // overflow: auto;
      .iconWrap {
        cursor: pointer;
      }
    }
  }
</style>
